<?php
/**
 * Created by PhpStorm.
 * User: zc
 * Date: 2019/8/5
 * Time: 23:36
 */
namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\logic\ChatLogic;
use app\common\logic\ChatManagerLogic;
use app\common\model\chat\ChatRoom;
use think\Db;
use think\Exception;

class ChatManager extends Api
{
    protected $noNeedLogin = ['create'];  //不能登陆方法
    protected $noNeedRight = '*';

    public function create() {
        $id = input('id/d', 0);
        $room = ChatRoom::get($id);
        if (!$room) {
            $this->error('参数错误');
        }

        if (!$room['room_id']) {
            Db::startTrans();
            try{
                $chat = new ChatManagerLogic();
                $roomid = $chat->create();
                $room->room_id = $roomid;
                $room->save();
                Db::commit();
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $auth = ChatLogic::getRole(UID, $room);
        if ($room['type'] == 3) {
            $this->error('直播已结束');
        }
        if ($room['type'] == 0 && $auth == config('chat_auth')['listener']) {
            $this->error('直播还未开始', -100);
        }
        $room =  (new ChatLogic())->getChatDetail($id, $this->auth->getUser());
        $this->success('roomid', $room);
    }


    //开放直播室
    public function open() {
        $room_id = input('room_id');
        $room = ChatRoom::get(['room_id' => $room_id]);
        if (!$room) {
            $this->error('参数错误');
        }
        if ($room->type == 1) {
            $this->error('正在直播');
        }
        if ($room->type == 3) {
            $this->error('直播结束');
        }
        $chat = new ChatManagerLogic();
        Db::startTrans();
        try{
            $chat->open($room_id);
            //重置为开放中
            $room->type = 1;
            $room->save();
            $this->success('成功');
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    //关闭直播室
    public function close() {
        $chat = new ChatManagerLogic();
        $room_id = input('room_id');
        $room = ChatRoom::get(['room_id' => $room_id]);
        if (!$room) {
            $this->error('参数错误');
        }
        $chat->close($room_id);
        $this->success('成功');
    }
}